package com.lzwork.gpt.service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.lzwork.gpt.db.dao.ModelDbMapper;
import com.lzwork.gpt.db.dao.SysInfoMapper;
import com.lzwork.gpt.db.entity.InfoEntity;
import com.lzwork.utility.logger.LOGGER;
import com.lzwork.utility.pair.IntTuple;

import lombok.AllArgsConstructor;

/**
 * @author LiZheng
 * @date 2023年12月21日 上午11:09:58
 */

public class VersionUpdate
{
	public VersionUpdate(SysInfoMapper infoMapper, ModelDbMapper modelMapper)
	{
		this.infoMapper = infoMapper;
		this.modelMapper = modelMapper;

		initFunMap();
	}

	SysInfoMapper infoMapper;
	ModelDbMapper modelMapper;

	@AllArgsConstructor
	class MethodInfo
	{
		IntTuple verTarget;
		Function<ModelDbMapper, Boolean> fun;
		String info;
	}

	List<MethodInfo> mathods = new ArrayList<>();

	final static IntTuple V_API_PARAM_DATA = new IntTuple(1, 1, 0);

	protected void initFunMap()
	{
		//
	}

	public void versionUpdate()
	{
		InfoEntity info = infoMapper.getInfo();
		if (info == null)
			return;

		List<IntTuple> doneUpdates = new ArrayList<>();

		int num = 0;
		for (MethodInfo sp : mathods)
		{
			int index = num++;

			if (sp == null)
				continue;

			try
			{
				IntTuple verLimit = sp.verTarget;

				if (!info.matchVersion(verLimit))
				{
					LOGGER.log(LOGGER.DB,
							"Call [" + sp.info + "] with version: " + info + " < " + sp.verTarget.toString(".", null));
					boolean done = sp.fun.apply(modelMapper);
					if (done)
						doneUpdates.add(verLimit);
				}

			} catch (Exception e)
			{
				String err = LOGGER.exceptionInfo(e);
				LOGGER.warn(LOGGER.DB, "Run version update job[" + index + "]-[" + sp.info + "] fail : " + err);
			}
		}
	}

	protected boolean writeApiDbData()
	{
		return true;
	}
}
